package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.service.IContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 合同表Service业务层处理
 *
 * @author zzyl
 * @date 2024-12-05
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询合同表
     *
     * @param id 合同表主键
     * @return 合同表
     */
    @Override
    public Contract selectContractById(Long id) {
        return getById(id);
    }

    /**
     * 查询合同表列表
     *
     * @param contract 合同表
     * @return 合同表
     */
    @Override
    public List<Contract> selectContractList(Contract contract) {
        return contractMapper.selectContractList(contract);
    }

    /**
     * 新增合同表
     *
     * @param contract 合同表
     * @return 结果
     */
    @Override
    public int insertContract(Contract contract) {
        return save(contract) ? 1 : 0;
    }

    /**
     * 修改合同表
     *
     * @param contract 合同表
     * @return 结果
     */
    @Override
    public int updateContract(Contract contract) {
        return updateById(contract) ? 1 : 0;
    }

    /**
     * 批量删除合同表
     *
     * @param ids 需要删除的合同表主键
     * @return 结果
     */
    @Override
    public int deleteContractByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除合同表信息
     *
     * @param id 合同表主键
     * @return 结果
     */
    @Override
    public int deleteContractById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 定时更新合同状态
     */
    @Override
    public void updateContractStatus() {
        //1.查询合同状态是未签约的,并且签约时间在当前时间之前的
        LambdaQueryWrapper<Contract> queryWrapper = Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getStatus, 0)
                .le(Contract::getSignDate, LocalDateTime.now());
        List<Contract> contractList = contractMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(contractList)) {
            //2.遍历集合更新状态
            contractList.forEach(contract -> {
                contract.setStatus(2L);
            });
            //3.更新合同信息
            updateBatchById(contractList);
        }
    }
}
